package com.pureut.quality.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.production.api.FeignProductionService;
import com.pureut.quality.domain.*;
import com.pureut.quality.domain.dto.*;
import com.pureut.quality.domain.vo.ActualValueVo;
import com.pureut.quality.domain.vo.PatrolInspectionDocumentVo;
import com.pureut.quality.domain.vo.QualityPatrolInspectionDocumentVo;
import com.pureut.quality.domain.vo.QualitySchemeConfigurationVo;
import com.pureut.quality.mapper.*;
import com.pureut.quality.service.IQualityInspectionService;
import com.pureut.quality.service.QualityInspectionDocumentService;
import com.pureut.quality.service.QualityPatrolInspectionDocumentService;
import com.pureut.quality.service.QualityPatrolTemporaryService;
import com.pureut.system.api.FeignService;
import com.pureut.system.api.domain.SysDictData;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.util.*;
import java.util.stream.Collectors;

/***
 * 巡检单据实现层
 * Author:C
 * Date:2023/02/10 15:33
 * @DESC
 */
@Service
public class QualityPatrolInspectionDocumentServiceImpl extends ServiceImpl<QualityPatrolInspectionDocumentMapper, QualityPatrolInspectionDocument> implements QualityPatrolInspectionDocumentService {

    @Resource
    QualityPatrolInspectionDocumentMapper qualityPatrolInspectionDocumentMapper;

    @Resource
    FeignService feignService;

    @Resource
    QualitySchemeConfigurationMapper qualitySchemeConfigurationMapper;

    @Resource
    QualitySchemeConfigurationDetailMapper qualitySchemeConfigurationDetailMapper;

    @Resource
    IQualityInspectionService qualityInspectionItemService;

    @Resource
    QualityPatrolTemporaryMapper qualityPatrolTemporaryMapper;

    @Resource
    QualityPatrolTemporaryService qualityPatrolTemporaryService;

    @Resource
    QualityCheckDocMapper qualityCheckDocMapper;

    @Resource
    FeignProductionService feignProductionService;

    @Resource
    PublicGoodsMapper publicGoodsMapper;

    @Resource
    QualityInspectionDocumentService qualityInspectionDocumentService;

    @Resource
    PublicProjectMapper publicProjectMapper;

    /**
     * 巡检单据列表
     *
     * @param qualityPatrolInspectionDocumentVo
     * @return
     */
    @Override
    @DataScope(deptAlias = "a")
    public List<QualityPatrolInspectionDocumentDto> getFreezeList(QualityPatrolInspectionDocumentVo qualityPatrolInspectionDocumentVo) {

        List<QualityPatrolInspectionDocumentDto> list = qualityPatrolInspectionDocumentMapper.getList(qualityPatrolInspectionDocumentVo);
        //生产阶别
        List<SysDictData> productionLevelArray = DictUtils.getDictCache("quality_production_level");
        Map<String, String> productionLevelMap = productionLevelArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //状态
        List<SysDictData> inspectionStatusArray = DictUtils.getDictCache("quality_patrol_inspection_status");
        Map<String, String> inspectionStatusMap = inspectionStatusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        for (QualityPatrolInspectionDocumentDto entity : list) {
            //生产阶别
            entity.setProductionLevelDict(productionLevelMap.get(entity.getProductionLevel()));
            //单据状态
            entity.setStatusDict(inspectionStatusMap.get(entity.getStatus()));
        }
        return list;
    }

    /**
     * 巡检单据新增
     *
     * @param qualityPatrolInspectionDocumentVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(QualityPatrolInspectionDocumentVo qualityPatrolInspectionDocumentVo) throws Exception {

        //生成保存巡检单
        QualityPatrolInspectionDocument qualityPatrolInspectionDocument = new QualityPatrolInspectionDocument();
        String authorityCoding = feignService.getAuthorityCoding("quality:inspecmanage:patrol:list");
        if (authorityCoding == null) {
            throw new GlobalException("该单据未进行配置，无法生成单据编码");
        }
        qualityPatrolInspectionDocument.setProductionLevel(qualityPatrolInspectionDocumentVo.getProductionLevel())
                .setProductionLine(qualityPatrolInspectionDocumentVo.getProductionLine())
                .setOrderNo(qualityPatrolInspectionDocumentVo.getOrderNo())
                .setMaterialCode(qualityPatrolInspectionDocumentVo.getMaterialCode())
                .setPatrolInspectionNo(authorityCoding)
                .setStatus(1)
                .setCreateBy(SecurityUtils.getUsername())
                .setCreateTime(new Date())
                .setDeptId(SecurityUtils.getDeptId())
                .setItemIds(qualityPatrolInspectionDocumentVo.getItemIds());
        save(qualityPatrolInspectionDocument);

        List<QualityPatrolTemporary> qualityPatrolTemporaryList = new ArrayList<>();
        // 保存物料信息需要水刺、分切查询接口,然后新增巡检物料信息检验表数据
        if (qualityPatrolInspectionDocumentVo.getProductionLevel() == 2) {
            //查询水刺制令单数据
            String orderNum = qualityPatrolInspectionDocumentVo.getOrderNo();
            AjaxResult detailList = feignProductionService.getDetailList(orderNum);
            List<SpunlaceOutputDetailDto> data = JSON.parseArray(JSON.toJSONString(detailList.get("data")), SpunlaceOutputDetailDto.class);
            if (data.size() < 1) {
                throw new GlobalException("未获取到明细数据");
            }
            for (SpunlaceOutputDetailDto entity : data) {
                QualityPatrolTemporary qualityPatrolTemporary = new QualityPatrolTemporary();
                qualityPatrolTemporary.setMaterialNumber(entity.getProductionNumber());
                qualityPatrolTemporary.setPatrolInspectionSheetNo(qualityPatrolInspectionDocument.getPatrolInspectionNo());
                qualityPatrolTemporary.setBatchNo(entity.getProductionBatch());
                qualityPatrolTemporary.setMaterialCode(entity.getMaterialCode());
                qualityPatrolTemporary.setInspectionMark(2);
                qualityPatrolTemporaryList.add(qualityPatrolTemporary);
            }
        } else if (qualityPatrolInspectionDocumentVo.getProductionLevel() == 3) {
            //查询分切制令单数据
            String documentNum = qualityPatrolInspectionDocumentVo.getOrderNo();
            AjaxResult ajaxResult = feignProductionService.detailList(documentNum);
            List<CutOrdersDocumentDetailDto> data = JSON.parseArray(JSON.toJSONString(ajaxResult.get("data")), CutOrdersDocumentDetailDto.class);
            if (data.size() < 1) {
                throw new GlobalException("未获取到明细数据");
            }
            for (CutOrdersDocumentDetailDto entity : data) {
                QualityPatrolTemporary qualityPatrolTemporary = new QualityPatrolTemporary();
                qualityPatrolTemporary.setMaterialNumber(entity.getMasterVolumeNum());
                qualityPatrolTemporary.setPatrolInspectionSheetNo(qualityPatrolInspectionDocument.getPatrolInspectionNo());
                qualityPatrolTemporary.setBatchNo(entity.getBatchNo());
                qualityPatrolTemporary.setMaterialCode(entity.getMaterialCode());
                qualityPatrolTemporary.setInspectionMark(2);
                qualityPatrolTemporaryList.add(qualityPatrolTemporary);
            }
        } else {
            //查询脱脂制令单数据
            String degreasOrderNumber = qualityPatrolInspectionDocumentVo.getOrderNo();
            AjaxResult ajaxResult = feignProductionService.getDegreasOrderDetailList(degreasOrderNumber);
            List<DegreasOutputDetailDto> data = JSON.parseArray(JSON.toJSONString(ajaxResult.get("data")), DegreasOutputDetailDto.class);
            if (data.size() < 1) {
                throw new GlobalException("未获取到明细数据");
            }
            for (DegreasOutputDetailDto entity : data) {
                QualityPatrolTemporary qualityPatrolTemporary = new QualityPatrolTemporary();
                qualityPatrolTemporary.setMaterialNumber(entity.getMaterialNumber());
                qualityPatrolTemporary.setPatrolInspectionSheetNo(qualityPatrolInspectionDocument.getPatrolInspectionNo());
                qualityPatrolTemporary.setBatchNo(entity.getBatchNumber());
                qualityPatrolTemporary.setMaterialCode(entity.getMaterialCode());
                qualityPatrolTemporary.setInspectionMark(2);
                qualityPatrolTemporaryList.add(qualityPatrolTemporary);
            }
        }
        return qualityPatrolTemporaryService.saveBatch(qualityPatrolTemporaryList);
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByIds(String ids) {
        List<String> idStr = Arrays.asList(ids.split(","));
        if (idStr.size() < 1) {
            throw new GlobalException("至少勾选一条数据");
        }
        List<QualityPatrolInspectionDocument> qualityPatrolInspectionDocuments = qualityPatrolInspectionDocumentMapper.selectList(new QueryWrapper<QualityPatrolInspectionDocument>().lambda().in(QualityPatrolInspectionDocument::getId, idStr));
        for (QualityPatrolInspectionDocument entity : qualityPatrolInspectionDocuments) {
            if (entity.getStatus() != 1) {
                throw new GlobalException("只能操作待检验的单据");
            }
        }
        //同时删除巡检物料信息检验表信息
        for (QualityPatrolInspectionDocument documentEntity : qualityPatrolInspectionDocuments) {
            List<QualityPatrolTemporary> qualityPatrolTemporaries = qualityPatrolTemporaryMapper.selectList(new QueryWrapper<QualityPatrolTemporary>().lambda().eq(QualityPatrolTemporary::getPatrolInspectionSheetNo, documentEntity.getPatrolInspectionNo()));
            if (qualityPatrolTemporaries.size() > 0) {
                qualityPatrolTemporaryMapper.deleteBatchIds(qualityPatrolTemporaries);
            }
        }
        //删除巡检单据
        return qualityPatrolInspectionDocumentMapper.deleteBatchIds(qualityPatrolInspectionDocuments) > 0;
    }

    /**
     * 获取检验项目数据(新增时)
     *
     * @param qualitySchemeConfigurationVo
     * @return
     */
    @Override
    public List<QualityInspectionDto> getItemMessage(QualitySchemeConfigurationVo qualitySchemeConfigurationVo) {

        List<QualitySchemeConfigurationDetail> details = null;
        //根据阶别、类别、方案类型、物料编码查询检验项目
        Long byCodeIds = qualitySchemeConfigurationMapper.getConfigurationListByCode(qualitySchemeConfigurationVo);
        if (byCodeIds != null) {
            //获取该id下的明细
            details = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().in(QualitySchemeConfigurationDetail::getInspectionId, byCodeIds));
        } else {
            //根据阶别、类别、方案类型、物料类别查询检验项目
            Long byCategoryIds = qualitySchemeConfigurationMapper.getConfigurationListByCategory(qualitySchemeConfigurationVo);
            if (byCategoryIds != null) {
                //获取该id下的明细
                details = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().in(QualitySchemeConfigurationDetail::getInspectionId, byCategoryIds));
            }
        }
        if (details == null || details.size() < 1) {
            throw new GlobalException("没有查询到对应的检验项目");
        }
        List<QualityInspectionDto> qualityInspectionDtoList = new ArrayList<>();

        for (QualitySchemeConfigurationDetail entity : details) {
            //获取检验项目
            QualityInspection byId = qualityInspectionItemService.getById(entity.getInspectionId());

            QualityInspectionDto qualityInspectionDto = new QualityInspectionDto();
            qualityInspectionDto.setItemCode(byId.getItemCode());
            qualityInspectionDto.setItemName(byId.getItemName());
            qualityInspectionDto.setItemControlMode(String.valueOf(byId.getItemControlMode()));
            qualityInspectionDto.setItemLowerLimit(entity.getLowerLimitValue());
            qualityInspectionDto.setItemUpperLimit(entity.getUpperLimitValue());
            qualityInspectionDto.setItemUnit(byId.getItemUnit());

            qualityInspectionDtoList.add(qualityInspectionDto);
        }
        return qualityInspectionDtoList;
    }

    /**
     * 样本检验（下方列表）
     *
     * @param qualitySchemeConfigurationVo
     * @return
     */
    @Override
    public List<SampleInspectionDto> getSampleDownList(QualitySchemeConfigurationVo qualitySchemeConfigurationVo) {

//        List<QualitySchemeConfigurationDetail> details = null;
//        //根据阶别、类别、方案类型、物料编码查询检验项目
//        List<Long> byCodeIds = qualitySchemeConfigurationMapper.getConfigurationListByCode(qualitySchemeConfigurationVo);
//        if (byCodeIds.size() > 0) {
//            //获取该id下的明细
//            details = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().in(QualitySchemeConfigurationDetail::getInspectionId, byCodeIds));
//        } else {
//            //根据阶别、类别、方案类型、物料类别查询检验项目
//            List<Long> byCategoryIds = qualitySchemeConfigurationMapper.getConfigurationListByCategory(qualitySchemeConfigurationVo);
//            if (byCategoryIds.size() > 0) {
//                //获取该id下的明细
//                details = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().in(QualitySchemeConfigurationDetail::getInspectionId, byCategoryIds));
//            }
//        }
//        if (details == null || details.size() < 1) {
//            throw new GlobalException("没有查询到对应的检验项目");
//        }
//        //获取单据配置信息
//        QualityCheckDoc qualityCheckDoc = qualityCheckDocMapper.selectOne(new QueryWrapper<QualityCheckDoc>().lambda().eq(QualityCheckDoc::getItemRank, qualitySchemeConfigurationVo.getItemRank()).eq(QualityCheckDoc::getMaterialType, qualitySchemeConfigurationVo.getCategory()));
        QualityPatrolInspectionDocument qualityPatrolInspectionDocument = getById(qualitySchemeConfigurationVo.getId());
        List<String> itemIds = Arrays.asList(qualityPatrolInspectionDocument.getItemIds().split(","));
        List<SampleInspectionDto> sampleInspectionDtoList = new ArrayList<>();

        //管控方式
        List<SysDictData> controlModeArray = DictUtils.getDictCache("quality_item_control_mode");
        Map<String, String> controlModeMap = controlModeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        for (String entity : itemIds) {
            //获取检验项目
//            QualityInspection byId = qualityInspectionItemService.getById(Long.parseLong(entity));
            PublicProject publicProject = publicProjectMapper.selectOne(new QueryWrapper<PublicProject>().lambda().eq(PublicProject::getItemId, entity));
            SampleInspectionDto sampleInspectionDto = new SampleInspectionDto();
            sampleInspectionDto.setItemName(publicProject.getItemName())
                    .setItemDetectionMode(String.valueOf(publicProject.getItemDetectionMode()))
                    .setItemCheckContent(publicProject.getItemCheckContent())
                    .setItemControlMode(String.valueOf(publicProject.getItemControlMode()))
                    .setItemControlModeDict(controlModeMap.get(String.valueOf(publicProject.getItemControlMode())))
                    .setItemUnit(publicProject.getItemUnit())
                    .setItemLowerLimit(publicProject.getItemLowerLimit())
                    .setItemUpperLimit(publicProject.getItemUpperLimit())
                    .setId(Long.parseLong(entity))
                    .setIsAverage(publicProject.getIsAverage());
            //获取样本个数
            int itemSampleNumber = publicProject.getItemSampleNumber();
            List<ActualValueVo> actualValueList = new ArrayList<>();
            for (int i = 1; i <= itemSampleNumber; i++) {
                ActualValueVo actualValueVo = new ActualValueVo();
                actualValueList.add(actualValueVo);
            }
            sampleInspectionDto.setActualValueList(actualValueList);

            sampleInspectionDtoList.add(sampleInspectionDto);
        }

        return sampleInspectionDtoList;
    }

    /**
     * 查看单据信息
     *
     * @param id
     * @return
     */
    @Override
    public QualityPatrolInspectionDocumentDto getViewById(Long id) {
        //生产阶别
        List<SysDictData> productionLevelArray = DictUtils.getDictCache("quality_production_level");
        Map<String, String> productionLevelMap = productionLevelArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        QualityPatrolInspectionDocumentDto viewById = qualityPatrolInspectionDocumentMapper.getViewById(id);

        viewById.setProductionLevelDict(productionLevelMap.get(viewById.getProductionLevel()));

        List<String> strings = Arrays.asList(viewById.getItemIds().split(","));

        //管控方式
        List<SysDictData> controlModeArray = DictUtils.getDictCache("quality_item_control_mode");
        Map<String, String> controlModeMap = controlModeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        List<SampleInspectionDto> sampleInspectionDtoList = new ArrayList<>();
        List<PublicProject> publicProjectList = publicProjectMapper.selectList(new QueryWrapper<PublicProject>().lambda().in(PublicProject::getItemId, strings));
        for (PublicProject entity : publicProjectList) {
            SampleInspectionDto sampleInspectionDto = new SampleInspectionDto();
            sampleInspectionDto.setItemName(entity.getItemName())
                    .setItemCode(entity.getItemCode())
                    .setItemDetectionMode(String.valueOf(entity.getItemDetectionMode()))
                    .setItemCheckContent(entity.getItemCheckContent())
                    .setItemControlMode(String.valueOf(entity.getItemControlMode()))
                    .setItemControlModeDict(controlModeMap.get(String.valueOf(entity.getItemControlMode())))
                    .setItemUnit(entity.getItemUnit())
                    .setItemLowerLimit(entity.getItemLowerLimit())
                    .setItemUpperLimit(entity.getItemUpperLimit())
                    .setId(entity.getItemId())
                    .setIsAverage(entity.getIsAverage());
            sampleInspectionDtoList.add(sampleInspectionDto);
        }
//        for (String entity : strings) {
//            //获取检验项目
//
////            QualityInspection byId = qualityInspectionItemService.getById(Long.parseLong(entity));
//
//            SampleInspectionDto sampleInspectionDto = new SampleInspectionDto();
//            sampleInspectionDto.setItemName(byId.getItemName())
//                    .setItemCode(byId.getItemCode())
//                    .setItemDetectionMode(String.valueOf(byId.getItemDetectionMode()))
//                    .setItemCheckContent(byId.getItemCheckContent())
//                    .setItemControlMode(String.valueOf(byId.getItemControlMode()))
//                    .setItemControlModeDict(controlModeMap.get(String.valueOf(byId.getItemControlMode())))
//                    .setItemUnit(byId.getItemUnit())
//                    .setItemLowerLimit(byId.getItemLowerLimit())
//                    .setItemUpperLimit(byId.getItemUpperLimit())
//                    .setId(Long.parseLong(entity))
//                    .setIsAverage(byId.getIsAverage());
//            sampleInspectionDtoList.add(sampleInspectionDto);
//        }
        viewById.setList(sampleInspectionDtoList);
        return viewById;
    }


    /**
     * 修改
     *
     * @param qualityPatrolInspectionDocumentVo
     * @return
     */
    @Override
    public boolean updatePatrolInspectionDocument(QualityPatrolInspectionDocumentVo qualityPatrolInspectionDocumentVo) {

        QualityPatrolInspectionDocument qualityPatrolInspectionDocument = getById(qualityPatrolInspectionDocumentVo.getId());
        if (qualityPatrolInspectionDocument.getStatus() == 1) {
            qualityPatrolInspectionDocument.setProductionLevel(qualityPatrolInspectionDocumentVo.getProductionLevel())
                    .setProductionLine(qualityPatrolInspectionDocumentVo.getProductionLine())
                    .setOrderNo(qualityPatrolInspectionDocumentVo.getOrderNo())
                    .setItemIds(qualityPatrolInspectionDocumentVo.getItemIds());

            return updateById(qualityPatrolInspectionDocument);
        } else {
            throw new GlobalException("只能修改状态为“待检验”的单据");
        }
    }

    /**
     * 获取检验项目数据(巡检单据新增时)
     *
     * @param patrolInspectionDocumentVo
     * @return
     */
    @Override
    public List<SampleInspectionDto> getPatrolInspectionDocument(PatrolInspectionDocumentVo patrolInspectionDocumentVo) {
        PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, patrolInspectionDocumentVo.getMaterialCode()));

        //获取该检验单下的检验项目列表
        QualitySchemeConfigurationVo qualitySchemeConfigurationVo = new QualitySchemeConfigurationVo();
        qualitySchemeConfigurationVo.setItemRank(patrolInspectionDocumentVo.getItemRank());
        qualitySchemeConfigurationVo.setCategory(publicGoods.getMaterialCategory());
        qualitySchemeConfigurationVo.setMaterialCode(publicGoods.getMaterialCode());
        qualitySchemeConfigurationVo.setMaterialCategory(publicGoods.getMaterialType());
        qualitySchemeConfigurationVo.setOrderNumber(patrolInspectionDocumentVo.getOrderNo());

        return qualityInspectionDocumentService.sampleInspection(qualitySchemeConfigurationVo);
    }
}
